<template>
  <div class="p-2 container">
    <el-card shadow="hover">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="任务名称" prop="patrolTaskName">
          <el-input v-model="queryParams.patrolTaskName" placeholder="请输入巡视任务名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
         <el-form-item label="执行时间">
          <el-date-picker v-model="queryParams.startEndTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-button v-hasPermi="['admin']" type="warning" plain style="width: 200px;" @click="handleExpiredUnfinishedTask">
      处理过期未完成的任务
    </el-button>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative; margin-top: 10px;">
      <el-tabs v-model:model-value="tabActiveName" @tab-change="tabChange">
        <el-tab-pane label="待执行" name="first">
          <el-table v-loading="loading" :data="taskExecutorList" style="flex: 1;" @selection-change="tableSelectionChange">
            <el-table-column label="任务执行编号" align="center" prop="cameraPatrolTaskExecutorCode" min-width="230" show-overflow-tooltip />
            <el-table-column label="巡视任务编码" align="center" prop="patrolTaskCode" min-width="210" show-overflow-tooltip />
            <el-table-column label="巡视任务名称" align="center" prop="patrolTaskName" min-width="150" show-overflow-tooltip />
            <el-table-column label="巡视路线" align="center" prop="patrolRouteName" min-width="150" show-overflow-tooltip />
            <el-table-column label="执行人" align="center" prop="executeUserName" min-width="120" show-overflow-tooltip />
            <el-table-column label="任务时长" align="center" prop="taskDuration" min-width="100" show-overflow-tooltip />
            <el-table-column label="开始时间" align="center" prop="startTime" min-width="180" show-overflow-tooltip />
            <el-table-column label="结束时间" align="center" prop="endTime" min-width="180" show-overflow-tooltip />
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button :disabled="scope.row.executeUserId!=userStore.userId" link type="primary" @click="openExecute(scope.row)">执行</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
        </el-tab-pane>

        <el-tab-pane label="已完成" name="second">
          <el-table v-loading="loading" :data="taskExecutorList" style="flex: 1;" @selection-change="tableSelectionChange">
            <el-table-column label="任务执行编号" align="center" prop="cameraPatrolTaskExecutorCode" min-width="230" show-overflow-tooltip />
            <el-table-column label="巡视任务编码" align="center" prop="patrolTaskCode" min-width="210" show-overflow-tooltip />
            <el-table-column label="巡视任务名称" align="center" prop="patrolTaskName" min-width="150" show-overflow-tooltip />
            <el-table-column label="巡视路线" align="center" prop="patrolRouteName" min-width="150" show-overflow-tooltip />
            <el-table-column label="执行人" align="center" prop="executeUserName" min-width="120" show-overflow-tooltip />
            <el-table-column label="任务时长" align="center" prop="taskDuration" min-width="100" show-overflow-tooltip />
            <el-table-column label="开始时间" align="center" prop="startTime" min-width="180" show-overflow-tooltip />
            <el-table-column label="结束时间" align="center" prop="endTime" min-width="180" show-overflow-tooltip />
            <el-table-column label="巡视时长" align="center" min-width="100" show-overflow-tooltip >
              <template #default="scope">
                {{ (scope.row.patrolDuration / 60).toFixed(2) }}分
              </template>
            </el-table-column>
            <el-table-column label="打卡时间" align="center" min-width="170">
              <template #default="scope">
                {{ scope.row.clockFlagStatus == 1 ? `${scope.row.clockTime}` : '未打卡' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="openDetail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--  详情  -->
    <el-drawer v-model="dialog.showDetail" :title="dialog.title" size="800px" append-to-body destroy-on-close>
      <Detail :camera-patrol-task-executor-id="cameraPatrolTaskExecutorId" @close="dialog.showDetail=false" />
    </el-drawer>

    <!--  执行弹框  -->
    <el-drawer v-model="dialog.showExecute" :title="dialog.title" size="100%" append-to-body destroy-on-close>
      <Execute :camera-patrol-task-executor-id="cameraPatrolTaskExecutorId" @close="dialog.showExecute=false" @submit="getList" />
    </el-drawer>

    <!-- 全屏 -->
    <el-dialog v-model="showCameraControl" title="设备详情" width="1000" append-to-body destroy-on-close>
      <camera-control :camera-data="selectedCamera" />
    </el-dialog>
  </div>
</template>

<script setup name="cameraPatrolTask" lang="ts">
import { implement, listcameraPatrolTaskExcuter } from '@/api/security/video-patrol/camera-patrol-task-executer';
import { cameraPatrolTaskExcuterVO } from '@/api/security/video-patrol/camera-patrol-task-executer/types';
import CameraControl from '@/views/security/video-monitor/real-time-monitor/components/CameraControl.vue';
import Execute from './components/Execute.vue';
import Detail from './components/Detail.vue';
import useUserStore from '@/store/modules/user';
import request from '@/utils/request'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const { camera_patrol_task_status, clock_flag } = toRefs<any>(proxy?.useDict('camera_patrol_task_status', 'clock_flag'));
const { ai_algorithm_type, alarm_type, event_type } = toRefs<any>(proxy?.useDict('ai_algorithm_type', 'alarm_type', 'event_type'));

const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedCamera = ref()
const showCameraControl = ref(false)
const queryFormRef = ref<ElFormInstance>();
const tabActiveName = ref('first')

const dialog = reactive({
  showEventReport: false,
  showExecute: false,
  showDetail: false,
  title: ''
});

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 20,
  patrolTaskName: undefined,
  statusList: ['0', '1'],
  startEndTime: [],
  params: { }
});

/** 查询巡视任务列表 */
const taskExecutorList = ref([]);
const loading = ref(true);
const getList = async () => {
  queryParams.value.startTime = queryParams.value.startEndTime.length > 0 ? queryParams.value.startEndTime[0] + ' 00:00:00' : null;
  queryParams.value.endTime = queryParams.value.startEndTime.length > 0 ? queryParams.value.startEndTime[1] + ' 23:59:59' : null;
  queryParams.value.executeUserId = userStore.userId;
  loading.value = true;
  const res = await listcameraPatrolTaskExcuter(queryParams.value).finally(()=> { loading.value = false; })
  taskExecutorList.value = res.rows;
  total.value = res.total;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = { pageNum: 1, pageSize: queryParams.value.pageSize, statusList: queryParams.value.statusList }

  handleQuery();
}

/** 多选框选中数据 */
const tableSelectionChange = (selection: cameraPatrolTaskExcuterVO[]) => {
  ids.value = selection.map(item => item.cameraPatrolTaskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('camera/camera-patrol-task/export', {
    ...queryParams.value
  }, `camera-patrol-task_${new Date().getTime()}.xlsx`)
}

/** 标签页切换 */
const tabChange = (tab) => {
  if (tab === 'first') {
    queryParams.value.statusList = ['0', '1']
  } else if (tab === 'second') {
    queryParams.value.statusList = ['2']
  }
  getList()
}

/** 详情 */
const cameraPatrolTaskExecutorId = ref(null)

/**
 * 打开详情弹框
 */
const openDetail = async(row) => {
  cameraPatrolTaskExecutorId.value = row.cameraPatrolTaskExecutorId
  dialog.showDetail = true
  dialog.title = ''
}

/**
 * 打开执行弹窗
 */
const openExecute = async(row: any) => {
  cameraPatrolTaskExecutorId.value = row.cameraPatrolTaskExecutorId
  // 校验是否在开执行时间内
  proxy.$modal.loading('正在加载');
  const res = await implement(cameraPatrolTaskExecutorId.value).finally(() => { proxy.$modal.closeLoading() })
  if (res.code == 200) {
    dialog.title = row.patrolTaskName
    dialog.showExecute = true
  } else {
    proxy?.$modal.msgError(res.msg)
  }
}

/**
 * 处理过期未完成的任务
 */
const handleExpiredUnfinishedTask = ()=> {
  proxy.$modal.loading('正在处理，请稍候');
  request({
    url: '/camera/patrolTaskExecutor/handle-expired-unfinished-task',
    method: 'post'
  }).then((res: any)=> {
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('处理成功');
      getList()
    } else {
      proxy?.$modal.msgError(res.msg)
    }
  }).finally(()=> { proxy.$modal.closeLoading() })
}

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
    :deep(.el-card__header) {

    }
    :deep(.el-card__body) {
        height: 100%;
    }
    :deep(.pagination-container) {
      margin: 0;
      height: 50px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
    :deep(.el-tabs) {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 45px);
        .el-tab-pane {
          height: 100%;
          display: flex;
          flex-direction: column;
        }
      }
    }
</style>

